package live.hotel.dao.impl;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import live.common.PostParam;
import live.hotel.dao.IXmlManage;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;


public class XmlManage implements IXmlManage {
	String officeId = PostParam.HOTEL_OFFICE.toString();
	String passprot = PostParam.HOTEL_PWD.toString();
	String postUrl = PostParam.HOTEL_URL.toString();
	String headXml =new StringBuffer()
	.append("<?xml version=\"1.0\" encoding=\"GB2312\"?>\n").append("<Request>\n")
	.append("	<Source>\n")
	.append("		<RequestorID OfficeID=\""+officeId+"\" Passport=\""+passprot+"\" />\n")
	.append("		<RequestorPreferences Currency=\"CNY\">\n")
	.append("			<RequestMode>SYNCHRONOUS</RequestMode>\n")
	.append("		</RequestorPreferences>\n")
	.append("	</Source>\n").append("	<RequestDetails>\n").toString();
	Document doc = null;
	public Document getDataFromApi(String strXml)
			throws Exception {
		strXml = headXml + strXml;
		URL url = new URL(postUrl);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setRequestProperty("Content-Type", "text/xml;charset=gbk");
		conn.setRequestMethod("POST");
		conn.setRequestProperty("Content-Length", String.valueOf(strXml
				.length()));
		conn.setConnectTimeout(5000);
		conn.setDoOutput(true);
		OutputStream os = conn.getOutputStream();
		os.write(strXml.toString().getBytes());
		os.flush();
		os.close();
		return resultToXml(conn);
	}

	public Document getDataFromXmlUrl(String xmlUrl) throws Exception {
		URL url = new URL(xmlUrl);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.connect();
		return resultToXml(conn);
	}
	
	Document resultToXml(HttpURLConnection conn) throws Exception{
		BufferedReader br = new BufferedReader(new InputStreamReader(conn
				.getInputStream()));
		String line;
		String result = "";
		while ((line = br.readLine()) != null) {
			result += "\n" + line;
		}
		br.close();
		doc = DocumentHelper.parseText(result.trim());
		if(doc.asXML().indexOf("<Errors")<0){
		return doc;
		}else{return null;}
	}
}
